<template>
  <div class="fileField">
    <template>
      <div style="padding: 10px 0">{{ itemdata.sTitle }}</div>
      <input type="hidden" v-model="itemdata.valuehidden" />
      <input type="hidden" v-model="itemdata.value" />
      <van-uploader
        :before-read="beforeRead"
        :disabled="itemdata.sEditable === 'false'"
        placeholder="请选择文件"
        v-model="itemdata.valuelist"
        :after-read="onFileHead"
        @delete="delFileHead"
        accept="*"
        multiple
        :name="itemdata.sField"
      >
        <template #preview-cover="{ file, url }">
          <div
            class="preview-cover van-ellipsis"
            @click.stop="downloadByUrl(file.name)"
          >
            <!-- {{ url }} -->
            <van-icon name="down" />
            下载文件
          </div>
        </template>
      </van-uploader>
    </template>
    <!-- <template v-else>
      <van-cell  :title="itemdata.sTitle">
        <template #default>
          <div v-html="itemdata.value"></div>
        </template>
      </van-cell>
    </template> -->
  </div>
</template>
<script>
import { Toast } from "vant";
import Vue from "vue";
Vue.use(Toast);
export default {
  props: {
    jsondata: {
      type: Object,
      required: false,
    },
    itemdata: {
      type: Object,
      required: false,
    },
    ishead: {
      type: Boolean,
      default: false,
    },
    index: {
      type: Number,
      required: false,
    },
  },
  data() {
    return {
      fileList: [],
      oldNameStr: this.itemdata.value || "",
      newNameStr: this.itemdata.valuehidden || "",
    };
  },
  methods: {
    downloadByUrl(filename) {
      const index = this.oldNameStr.split(";").indexOf(filename);
      const newname = this.newNameStr.split(";")[index];

      if (newname) {
        const url =
          window.location.protocol +
          "//" +
          window.location.hostname +
          (window.location.port ? ":" + window.location.port : "/");
        console.log("url", url);
        window.location.href = `${url}/userfile/default/attach/${newname}`;
      }
    },
    beforeRead(file) {
      // if (file.type !== 'application/pdf') {
      //   Toast('请上传pdf格式文件')
      //   return false
      // }
      return true;
    },
    onFileHead(file, detail) {
      // 上传
      let deviceFile = [];
      let formData = new FormData();
      if (Array.isArray(file)) {
        deviceFile = file;
      } else {
        deviceFile.push(file);
      }
      for (let i = 0; i < deviceFile.length; i++) {
        formData.append("file" + i, deviceFile[i].file, deviceFile[i].name);
      }
      const toast = Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "等待上传中...请稍候",
      });
      this.axios({
        method: "post",
        url: "/api/upload.filedo",
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
        .then((res) => {
          toast.clear();
          if (res.data.flag === "0") {
            let fileInfo = res.data.fileInfo;

            this.oldNameStr += fileInfo[0].oldname + ";";
            this.newNameStr += fileInfo[0].newname + ";";
            const newnameList = fileInfo[0].newname.split(";");
            const oldnameList = fileInfo[0].oldname.split(";");
            const fileList = newnameList.map((item, index) => {
              const file = { newname: item, oldname: oldnameList[index] };
              return file;
            });
            this.fileList = [...this.fileList, ...fileList];
            this.$emit('giveFileList',this.fileList)
            if (this.ishead) {
              for (
                let headIdx = 0;
                headIdx < this.jsondata.head.length;
                headIdx++
              ) {
                let headData = this.jsondata.head[headIdx].groupvalue;
                for (let i = 0; i < headData.length; i++) {
                  if (headData[i].sField === detail.name) {
                    headData[i].valuehidden =
                      fileInfo[0].newname +
                      ";" +
                      (headData[i].valuehidden &&
                      headData[i].valuehidden != null &&
                      headData[i].valuehidden != undefined &&
                      headData[i].valuehidden != "undefined"
                        ? headData[i].valuehidden
                        : "");
                    headData[i].value =
                      fileInfo[0].oldname +
                      ";" +
                      (headData[i].value &&
                      headData[i].value != null &&
                      headData[i].value != undefined &&
                      headData[i].value != "undefined"
                        ? headData[i].value
                        : "");
                  }
                }
              }
            } else {
              // 目前只处理单子表（第一个子表）
              for (let key in this.jsondata.bodydata) {
                let headData = this.jsondata.bodydata[key][this.index];
                for (let i = 0; i < headData.length; i++) {
                  if (headData[i].sField === detail.name) {
                    headData[i].valuehidden =
                      fileInfo[0].newname +
                      ";" +
                      (headData[i].valuehidden &&
                      headData[i].valuehidden != null &&
                      headData[i].valuehidden != undefined &&
                      headData[i].valuehidden != "undefined"
                        ? headData[i].valuehidden
                        : "");
                    headData[i].value =
                      fileInfo[0].oldname +
                      ";" +
                      (headData[i].value &&
                      headData[i].value != null &&
                      headData[i].value != undefined &&
                      headData[i].value != "undefined"
                        ? headData[i].value
                        : "");
                  }
                }
                break;
              }
            }
            Toast("上传成功");
          } else {
            Toast("上传失败");
          }
        })
        .catch((res) => {
          //console.log(file)
        });
      // let headdata = this.jsondata.head[0].groupvalue
      //console.log(file)
      //console.log(detail)
    },
    delFileHead(file, detail) {
      if (this.ishead) {
        for (let headIdx = 0; headIdx < this.jsondata.head.length; headIdx++) {
          let headData = this.jsondata.head[headIdx].groupvalue;
          for (let i = 0; i < headData.length; i++) {
            if (headData[i].sField === detail.name) {
              let fileVal = headData[i].valuehidden.split(";");
              let fileTitle = headData[i].value.split(";");
              for (let j = 0; j < fileTitle.length; j++) {
                if (fileTitle[j] === file.file.name) {
                  fileVal[j] = "";
                  fileTitle[j] = "";
                }
              }
              let fileVal1 = "";
              let fileTitle1 = "";
              for (let j = 0; j < fileTitle.length; j++) {
                if (fileTitle[j] !== "") {
                  fileVal1 += fileVal[j] + ";";
                  fileTitle1 += fileTitle[j] + ";";
                }
              }
              headData[i].valuehidden = fileVal1;
              headData[i].value = fileTitle1;
            }
          }
        }
      } else {
        for (let key in this.jsondata.bodydata) {
          let headData = this.jsondata.bodydata[key][this.index];
          for (let i = 0; i < headData.length; i++) {
            if (headData[i].sField === detail.name) {
              let fileVal = headData[i].valuehidden.split(";");
              let fileTitle = headData[i].value.split(";");
              for (let j = 0; j < fileTitle.length; j++) {
                if (fileTitle[j] === file.file.name) {
                  fileVal[j] = "";
                  fileTitle[j] = "";
                }
              }
              let fileVal1 = "";
              let fileTitle1 = "";
              for (let j = 0; j < fileTitle.length; j++) {
                if (fileTitle[j] !== "") {
                  fileVal1 += fileVal[j] + ";";
                  fileTitle1 += fileTitle[j] + ";";
                }
              }
              headData[i].valuehidden = fileVal1;
              headData[i].value = fileTitle1;
            }
          }
          break;
        }
      }
      Toast("删除成功");
      console.log( this.jsondata,8686)
    },
  },
};
</script>

<style scoped lang="less">
.fileField {
  padding: 10px 5px;
  border-bottom: 1px solid #eee;
  background: #fff;
  // padding: 10px 16px;
  color: #646566;
  line-height: 16px;
  font-size: 16px;
  font-weight: 400;
}
.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
</style>
